package com.mjlf.mjatis.result;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.mjlf.mjatis.util.Json2Entity;

import java.util.HashSet;
import java.util.Set;

/**
 * @ClassName ResultMapUitl
 * @Author mjlft
 * @Date 2020/5/31 16:12
 * @Version 1.0
 * @Description Result工具类
 */
public final class ResultMapUtil {

    /**
     * 将ResultMap Json配置转换为ResultMap集合配置
     * @param resultMapArray
     * @return
     */
    public static Set<ResultMap> parse(JSONArray resultMapArray) throws IllegalAccessException, InstantiationException, ClassNotFoundException {
        if(resultMapArray != null){
            Set<ResultMap> resultMaps = new HashSet<>((int)(resultMapArray.size() / 0.75) + 1);
            for(int i = 0; i < resultMapArray.size(); i ++){
                ResultMap resultMap = parse(resultMapArray.getJSONObject(i));
                if(resultMap != null){
                    resultMaps.add(resultMap);
                }
            }
            return resultMaps;
        }
        return null;
    }

    public static ResultMap parse(JSONObject resultMapJson) throws InstantiationException, IllegalAccessException, ClassNotFoundException {
        if(resultMapJson != null){
            ResultMap resultMap = Json2Entity.getEntity(resultMapJson, ResultMap.class);
            if(resultMap != null){
                resultMap.setClazz(Class.forName(resultMap.getClassName()));
                return resultMap;
            }
        }
        return null;
    }
}
